import { upperFirst } from 'lodash-es';
import { getDataInterfaceRes } from '@/api/systemData/dataInterface';
import { useBaseStore } from '@/store/modules/base';
import { computed, reactive } from 'vue';

interface State {
  searchSchemas: any[];
}

export const useReport = (formApi: any = {}) => {
  const baseStore = useBaseStore();
  const state = reactive<State>({
    searchSchemas: [],
  });

  const searchSchemas = computed(() => state.searchSchemas);

  // 更新图表数据
  function getRealEchart(echarts, chartData) {
    if (!echarts) return null;
    Object.keys(echarts).forEach(key => {
      const chart = echarts[key];
      const dataList = chartData.filter(o => o.drawingId === key);
      let data: any = {};
      if (dataList.length) data = dataList[0].field;
      const { classifyNameField = [], seriesDataField = [], seriesNameField = [] } = data;
      // 柱状图和线性图
      if (['bar', 'line'].includes(chart.echartType)) {
        const series = seriesDataField?.map((o, index) => {
          return {
            name: seriesNameField[index],
            data: o,
            type: chart.echartType,
            ...(chart.echartType === 'line' ? { smooth: chart.option.line?.smooth } : {}),
          };
        });
        chart.option.series = series;
        chart.option.legend.data = seriesNameField;
        chart.option.xAxis.data = classifyNameField;
      }
      // 饼图
      if (chart.echartType === 'pie') {
        const series = seriesDataField?.map((o, index) => {
          const data = o?.map((item, sIndex) => {
            return {
              value: item,
              name: classifyNameField?.[sIndex],
            };
          });
          return {
            name: seriesNameField[index],
            type: 'pie',
            radius: '50%',
            center: [chart.option.seriesCenter.seriesCenterLeft + '%', chart.option.seriesCenter.seriesCenterTop + '%'],
            roseType: chart.option.pie?.roseType,
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)',
              },
            },
          };
        });
        chart.option.series = series;
        chart.option.legend.data = seriesNameField;
      }
      // 雷达图
      if (chart.echartType === 'radar') {
      }
    });
    return echarts;
  }
  // 获取搜索内容
  function getSearchSchema(queryList) {
    if (!queryList.length) return (state.searchSchemas = []);
    const list = queryList[0].queryList || [];
    const schemas = list.map((option: any) => {
      const { label, type, vModel, config } = option;
      const field = vModel?.replace('.', '-');
      if (type === 'select') {
        config.fieldNames = { value: config.propsValue };
      }
      return {
        field,
        label,
        component: upperFirst(type),
        componentProps: config,
      };
    });
    // 异步更新 select 类型字段的 schema
    for (const cur of schemas) {
      const config = cur?.componentProps || {};
      if (cur?.component === 'Select') {
        if (config.dataType === 'dictionary' && config.dictionaryType) {
          baseStore.getDicDataSelector(config.dictionaryType).then(res => {
            formApi.updateSchema([{ field: cur.field, componentProps: { options: res } }]);
          });
        } else if (config.dataType === 'dynamic' && config.propsUrl) {
          const query = { paramList: config.templateJson || [] };
          getDataInterfaceRes(config.propsUrl, query).then(res => {
            const data = Array.isArray(res.data) ? res.data : [];
            formApi.updateSchema([{ field: cur.field, componentProps: { options: data } }]);
          });
        }
      }
    }
    state.searchSchemas = schemas;
  }

  return {
    getRealEchart,
    getSearchSchema,
    searchSchemas,
  };
};
